var $productDetailTable = $('#productDetailTable');
var $activityProductTable = $('#activityProductTable');
var $giftDetailTable = $('#giftDetailTable');
var $findAudit = $('#findAudit');

// 产品详细
var $viewSumption=$("#viewSumption");
var $adjustMent=$("#adjustMent");
var imgContractSrc,imgReviewSrc;
var seeimgContractSrc,seeimgReviewSrc
// 合同附件
var annexFilePath;
// 审核附件
var examineFilePath;
var clueFollowId,opportunityIds;//跟进id,商机id
var pageIndex=1,pageSize=5,totalNum;//当前商机动态分页索引初始化为1,//商机动态每次加载5条,//商机动态总数据量


//合同id
// var contractId =sessionStorage.getItem('contractId');
var contractId =$("#contractId").val()
//订单id
// var orderId =sessionStorage.getItem('orderId');
var orderId =$("#orderId").val();
var url = $('.contractReview').attr('href');
// location.reload()selectContractById
$(function () {

    initViewList()
    initAdjustList()
    //获取页面跳转的合同id和订单id

    // var result = url.split("?")[1];
    // var keyValue = result.split("&");
    // var obj = {};
    // for (var i = 0; i < keyValue.length; i++) {
    //     var item = keyValue[i].split("=");
    //     obj[item[0]] = item[1];
    // }
    // contractId = obj.contractId;
    // orderId = obj.orderId;
    // contractId =sessionStorage.getItem('contractId');
    // orderId =sessionStorage.getItem('orderId');

    contractId =$("#contractId").val();
    orderId =$("#orderId").val();

    //回款日期
    $('#collectionDate').datepicker({
        language: "zh-CN",
        autoclose: true,
        clearBtn: true,
        todayHighlight: true,
        format: "yyyy-mm-dd"
    });
    /**
     * 创建时间
     */
    $('#creationData').datepicker({
        language:'zh-CN',
        autoclose: true,
        clearBtn: true,
        todayHighlight: true,
        format:"yyyy-mm-dd"
    })

    /**
     * 产品详情--分页列表页
     */
    //初始化产品详情
    productDetailTableListInit();
    //初始化活动产品
    activityProductTableInit();
    //赠品初始化
    giftDetailTableInit();
    //审核处理
    findAuditTableInit();
    //上传图片
    // uploadImg()

    // getCustomerSelect(contract)
    //初始化数据
    initData()
    //表单校验
    formValidator()
//    合同类型
//    优惠卷
    couponTableInit()



    //拖拽add
    var times = 0;
    var x_left='',y_top=''
    $('#model-add-mousedown').mousedown(function(e){
        times++

        // e.pageX
        var positionDiv = $(this).offset();
        var distenceX = e.pageX - positionDiv.left;
        var distenceY = e.pageY - positionDiv.top;

        if(times==1){
            x_left=positionDiv.left
            y_top=positionDiv.top
        }

        // console.log(positionDiv,e.pageX,e.pageY,'---',distenceX,distenceY,e.pageX-distenceX,e.pageY-distenceY)
        //alert(distenceX)
        // alert(positionDiv.left);
        $(document).mousemove(function(e){
            var x = e.pageX - distenceX;
            var y = e.pageY - distenceY;
            if(x<0){
                x=0;
            }else if(x>$(document).width()-$('#model-add-mousedown').outerWidth(true)){
                x = $(document).width()-$('#model-add-mousedown').outerWidth(true);
            }
            if(y<0){
                y=0;
            }else if(y>$(document).height()-$('#model-add-mousedown').outerHeight(true)){
                y = $(document).height()-$('#model-add-mousedown').outerHeight(true);
            }

            $('#model-add-mousedown').css({
                'left':x-x_left+'px',
                'top':y-y_top+'px'
            });
        });
        $(document).mouseup(function(){
            $(document).off('mousemove');
        });
    });

    // 合作开发人员
    cooperateTable();
    $('#cooperateModal').on('show.bs.modal', function () {
        $('#cooperateTable').bootstrapTable('showLoading');
        viewCooperate();
        $('body').removeClass('filter-blur');
    });
})

/**
 * 功能：查看合作开发人员信息
 * */
function viewCooperate() {
    $.ajax({
        url: '/customerContract/selectContractCoDeveloperById',
        type: 'GET',
        dataType: 'json',
        data: {
            contractId
        },
        success: function (data) {
            if (data.code == '000000') {
                $('#cooperateTable').bootstrapTable('hideLoading').bootstrapTable('load', data.data);
            } else {
                $.alert('获取开发人员信息出错，代码：' + data.code);
            }
        },
        error: function (err) {
            $.alert('获取开发人员信息失败！');
            console.log(err);
        }
    })
}

// 初始化合作开发人员信息列表
function cooperateTable() {
    $('#cooperateTable').bootstrapTable({
        classes: 'table table-bordered table-hover table-striped',
        striped: true,                      // 是否显示行间隔色
        undefinedText: '-',                 // cell没有值时显示
        pagination: true,                   // 是否显示分页
        pageSize: '5',                      // 每页的记录行数
        pageNumber: 1,                      // 初始化加载第1页，默认第1页
        pageList: ['5', '10'],              // 可供选择的每页的行数
        columns: [
            {title: '合作开发人员', field: 'userName', align: 'left', valign: 'middle'},
            {title: '所属分公司', field: 'companyName', align: 'left', valign: 'middle'},
            {title: '分配金额', field: 'allocationMount', align: 'left', valign: 'middle'},
        ]
    });
}

function TelCall(){
    // var tel='tel://'+'18811355753'
    // var tel='tel://'+$('#contactDetails').html()

    // $("#tel-dial").attr("href",tel)

}

//显示
$('#myModal').modal('show')

//隐藏
$('#myModal').modal('hide')




//显示预览
$('#myModalPreview').modal('show')

//隐藏
$('#myModalPreview').modal('hide')

function removeModal() {
    location.reload()
    // $("#contractReviewTableList").load(location.href+" #contractReviewTableList");
}

//
// this.$element.on('click.dismiss.bs.modal', '[data-dismiss="modal"]:first', $.proxy(this.hide, this))
// this.$element.on('click.dismiss.bs.modal', '[data-dismiss="modal"]:last', $.proxy(this.hide, this))

//预览按钮
function imgContract() {
    // parent.$(parent.document).data('multitabs').create({
    //     iframe: true,                                // 指定为iframe模式，当值为false的时候，为智能模式，自动判断（内网用ajax，外网用iframe）。缺省为false。
    //     title: title,                     // 标题（可选），没有则显示网址
    //     url: url                   // 链接（必须），如为外链，强制为info页
    // }, true);// true 则激活新增的tab页

    $(".imgPreview").html(imgContractSrc)

}
function imgReview() {

    $(".imgPreview").html(imgReviewSrc)

}
//隐藏
function closePreview(){
    // $('#myModalPreview').css({'display':"none"})
    $('#myModalPreview').hide()
}

/**
 * --列表序列号
 */
function indexFormat(value, row, index) {
    return index + 1;
}

$("#editSaveSwitch").on('click',function (event) {
    var bootstrapValidator = $("#customerForm").data('bootstrapValidator');
    bootstrapValidator.validate();
    if (!bootstrapValidator.isValid()) {
        return;
    };
    if($("#editSaveSwitch").text()=='编辑'){
        $("#contractType").attr("disabled",false)
        $("#contractDate").attr("disabled",false)
        $("#contactName").attr("disabled",false);//客户联系人
        $("#contactDetails").attr("disabled",false);//联系方式
        $("#customerEmail").attr("disabled",false)//客户邮箱
        $('#editSaveSwitch span').html('保存')
    }else{
        $("#contractType").attr("disabled",true)
        $("#contractDate").attr("disabled",true)
        $("#contactName").attr("disabled",true);//客户联系人
        $("#contactDetails").attr("disabled",true);//联系方式
        $("#customerEmail").attr("disabled",true)//客户邮箱
        $('#editSaveSwitch span').html('编辑')

        //合同起止日期截取
        var contractPeriodValidity = $("#contractDate").val().split('至');
        // 起止时间-开始时间
        if(!$.trim(contractPeriodValidity[0]) || $.trim(contractPeriodValidity[0])=='--'){
            var contractStartDate = ''
        }else{
            var contractStartDate = $.trim(contractPeriodValidity[0]);
        }
        // 起止时间-结束时间
        if(!$.trim(contractPeriodValidity[1]) || $.trim(contractPeriodValidity[1])=='--'){
            var contractEndDate = ''
        }else{
            var contractEndDate = $.trim(contractPeriodValidity[1]);
        }
        var jsonData={
            // contractId:sessionStorage.getItem('contractId'),
            contractId:$("#contractId").val(),
            contractStartDate:contractStartDate,
            contractEndDate:contractEndDate,
            contractType:$("#contractType").find('option:selected').val(),
            contactName:$("#contactName").val(),
            contactDetails:$("#contactDetails").val(),
            customerEmail:$("#customerEmail").val(),
            orderId:$("#orderId").val()
        };
        $.ajax({
            type:"post",
            url:"/customerContract/updateContractDetail",
            contentType: "application/json;charset=utf-8",
            data: JSON.stringify(jsonData),
            dataType: 'json',
            async:false,
            success:function (data,status) {
                if(data.code=='000000'){
                    $.alert(data.message);
                } else if (data.code == 'CR0001') {
                    $.alert({
                        title: '提醒',
                        content: '此合同已经被审核通过，不能编辑合同详情！',
                        buttons: {
                            confirm: {
                                text: '确认',
                                btnClass: 'btn-primary',
                                action: function () {
                                    // 刷新页面
                                    window.location.reload();
                                }
                            }
                        }
                    });
                } else{
                    $.alert(data.message);
                }
            },
            error: (function (res) {
                $.alert("保存失败");
            })
        })


    }
})

//初始化数据
function initData() {
    $.ajax({    // 获取活动相关产品
        type: "get",
        url: "/contractReview/getContractReviewDetail?contractId=" + contractId,
        async: false,
        success: function (data, status) {
            if(data.code == '000000') {
                console.log(data)
                clueFollowId = data.data.followRecordId;//跟进id
                opportunityIds = data.data.opportunityId;//商机id
                if(clueFollowId===null&&opportunityIds===null){
                    $("#followBtnCon").hide();
                }else if(clueFollowId===null){
                    $("#followUpDetail .followInfoContainer").hide();
                }else if(opportunityIds===null){
                    $("#followUpDetail .businessDynamics").hide();
                };
                if(data.data.contractReviewStatus==2 || data.data.contractReviewStatus==3){
                    $("#editSaveSwitch").hide()
                }else{
                    $("#editSaveSwitch").show()
                }
                // 合同附件URL
                annexFilePath = data.data.contractAnnexAccessUrl;
                // 审核附件RUL
                examineFilePath = data.data.reviewAnnexAccessUrl;
                // 判断是否存在附件
                if (annexFilePath) {
                    $('.annex-group').show();
                    $('.annex-group button').prop('disabled', false);
                }
                if (examineFilePath) {
                    $('.approval').show();
                    $('.approval button').prop('disabled', false);
                    $('#contractReviewNotes').html(data.data.contractReviewNotes);
                }

                // 合同起止日期初始化
                timeData('contractDate','contractDate','customerForm');

                $('#contractNumber').html(data.data.contractNumber)
                $('#customerNameRepeat').html(data.data.customerName)
                $('#customerId').val(data.data.customerId)
                $('#customerType').val(data.data.customerType)
                $('#contactName').val(data.data.contactName)
                var dataTel=data.data.contactDetails
                if(dataTel!=null){
                    // $('#contactDetails').val(dataTel.slice(0,3)+'-'+dataTel.slice(3,7)+'-'+dataTel.slice(7))
                    $('#contactDetails').val(dataTel)
                }

                $('#customerEmail').val(data.data.customerEmail)
                $('#createPeopleName').html(data.data.createPeopleName)
                $('#createTm').html(data.data.createTm)
                $('#payBackDate').html(data.data.payBackDate)
                $('#followRecordName').html(data.data.followRecordName)
                $('#masterMembershipContract').html(data.data.masterMembershipContract)
                $('#masterMembershipContractId').val(data.data.masterMembershipContractId)
                if(data.data.masterMembershipContractStartTime != null){
                    $('#masterMembershipContractStartEndTime').html(data.data.masterMembershipContractStartTime+ ' 至 ' + data.data.masterMembershipContractEndTime)
                }
                //给会员主合同产品表格赋值
                setMasterMembershipContractProductList(data.data.productOrderDetailList);
                $('#opportunityName').html(data.data.opportunityName)
                $('#opportunityId').html(data.data.opportunityId)
                //$('#applyElectronicContract').html(data.data.applyElectronicContract == 0 ? '否' : '是')
                if(data.data.applyElectronicContract==0){
                    $('#applyElectronicContract').html('否')
                }else if(data.data.applyElectronicContract==1){
                    $('#applyElectronicContract').html('是')
                }
                $('#advancePostponementReason').html(data.data.advancePostponementReason)
                //$(this).closest('.file-group').find('[type="file"]')
                $("#contractType option[value='"+data.data.contractType+"']").attr("selected",'selected')
                if(!data.data.contractStartDate && !data.data.contractEndDate){
                    var contractDatetime = '-- 至 --'
                }else{
                    var contractDatetime = data.data.contractStartDate+' 至 '+ data.data.contractEndDate
                }
                $("#contractDate").val(contractDatetime)
                $('#paymentMethod').html(data.data.paymentMethod)
                //附件金额
                $('#orderSurcharge').html(data.data.orderSurcharge)
                $('#orderSurchargeRemark').html(data.data.orderSurchargeRemark)
                if ($('#orderSurcharge').html() == '' || $('#orderSurcharge').html() == '0') {
                    $('.surcharge-remarks').hide();
                } else {
                    $('.surcharge-remarks').show();
                }
                // 合计金额
                $('#contractTotalAmount').html(data.data.contractTotalAmount)
                $('#contractDiscountTotalAmount').html(data.data.contractDiscountTotalAmount)
                $('#contractReceivables').html(data.data.contractReceivables)
                $('#contractActualTotalAmount').html(data.data.contractActualTotalAmount)
                //备注
                $('#notes').html(data.data.contractReviewNotes)

                //订单编号
                $('#orderNumber').html(data.data.orderNumber)
                $('#orderStatus').html(data.data.orderStatus)


                // $('#contractNumber').html(data.data.contractNumber)

            }
        }
    });
}

function setMasterMembershipContractProductList(dataList){
    //先销毁表格
    $('#masterContractProduct').bootstrapTable('destroy');
    $('#masterContractProduct').bootstrapTable({
        classes: 'table table-bordered table-hover table-striped',
        dataType: "json",//数据类型
        striped: true,//是否显示行间隔色
        cache: false,//是否使用缓存
        showColumns: false,//显示隐藏列
        showRefresh: false,//显示刷新按钮
        showToggle: false,//切换显示样式
        showFooter: false,//显示Table脚部
        pagination: false,//是否显示分页
        showPaginationSwitch: false,//是否显示分页按钮
        clickToSelect: false,//是否启用点击选中行
        singleSelect: false,
        undefinedText: '-',//cell没有值时显示
        // 判断dataList是否为null
        data: dataList || {},
        columns: [
            {title: '序号', field: 'index', align: 'left', valign: 'middle', width: '60', formatter: indexFormat},
            {title: '产品名称',field: 'orderDetailName', align: 'left', valign: 'middle'},
            {title: '成交价格', field: 'productFinalPrice',align: 'left', valign: 'middle'}
        ]
    });
}
/**
 * 产品详情--分页列表页
 */
function productDetailTableListInit() {
    //先销毁表格
    $productDetailTable.bootstrapTable('destroy');
    $productDetailTable.bootstrapTable({
        classes: 'table table-bordered table-hover table-striped',
        url: '/order/selectCustomerProductOrderDetailList',//请求地址
        method: 'post',//请求方式
        contentType: "application/x-www-form-urlencoded",//请求内容类型
        dataType: "json",//数据类型
        striped: true,//是否显示行间隔色
        sortable: true,//是否启用排序
        sortOrder: "desc",//排序方式
        sortName: 'createTm',//排序字段
        cache: false,//是否使用缓存
        showColumns: false,//显示隐藏列
        showRefresh: false,//显示刷新按钮
        showToggle: false,//切换显示样式
        showFooter: false,//显示Table脚部
        pagination: true,//是否显示分页
        showPaginationSwitch: false,//是否显示分页按钮
        clickToSelect: false,//是否启用点击选中行
        singleSelect: false,
        minimumCountColumns: 2,//最少要显示的列数
        undefinedText: '',//cell没有值时显示
        sidePagination: "server",//分页方式：client客户端分页，server服务端分页
        uniqueId: 'productOrderDetailId',
        idField: 'orderRelationId',
        pageSize: 5,//每页的记录行数
        pageNumber: 1,//初始化加载第1页，默认第1页
        pageList: "[5]",//可供选择的每页的行数
        fixedColumns: true,     // 冻结列
        fixedNumber: 1,         // 左侧固定列
        fixedRightNumber: 1,    // 右侧固定列
        queryParams: function (params) {
            var temp = {
                pageSize: params.limit,         // 每页数据量
                pageIndex: (params.offset / params.limit) + 1,
                productOrderId:orderId,// $('#productOrderId').val(),
                productOrderDetailType: '1'
            };
            return temp;
        },
        columns: [
            {title: '主键', field: 'orderRelationId', visible: false},
            {title: '序号', field: 'index', align: 'left', valign: 'middle', width: '80',formatter: indexFormat},
            {title: '产品名称', field: 'orderDetailName', align: 'left', valign: 'middle', class: 'ellipsis'},
            {title: '产品原价', field: 'productOriginalPrice', align: 'left', valign: 'middle'},
            {title: '产品单价', field: 'productUnitPrice', align: 'left', valign: 'middle'},
            {title: '产品会员价', field: 'productMemberPrice', align: 'left', valign: 'middle'},
            {title: '产品成交价', field: 'productFinalPrice', align: 'left', valign: 'middle'},
            {title: '产品数量', field: 'productQuantity', align: 'left', valign: 'middle'},
            {title: '产品优惠金额', field: 'productPreferentialPrice', align: 'left', valign: 'middle',
                formatter: function (value, row) {
                    if (value < 0) {
                        return 0;
                    } else {
                        return value * row.productQuantity;
                    }
                }
            }
        ],
        responseHandler: function (result) {
            if (result.code == "000000") {
                var obj = {
                    "rows": result.data,
                    "total": result.totalRecords//总条数
                };
            } else {
                var obj = {
                    "total": 0,
                    "rows": [],
                }
            }
            return obj;
        },
        onLoadSuccess: function () {
            //加载成功时执行
            // table列可拖动宽度
            /*$('.JCLRgrips').remove();
            $('#productDetailTable').css({
                minWidth: $('#productDetailTable').width()
            })*/
            // }).colResizable({
            //     resizeMode: 'overflow',
            //     liveDrag: true,
            //     gripInnerHtml: "<div class='grip'></div>",
            //     draggingClass: "dragging",
            //     disabledColumns: [0],                                     // 禁止拖动的列
            //     postbackSafe: true,                                         // 刷新后保持拖动的宽度
            //     partialRefresh: true,                                       // 刷新表格之后继续保持可拖动功能
            //     flush: true,
            //     minWidth: 80,
            // });
        },
    });
}


/**
 * 活动产品 --分页列表页
 */
function activityProductTableInit() {
    //先销毁表格
    $activityProductTable.bootstrapTable('destroy');
    $activityProductTable.bootstrapTable({
        classes: 'table table-bordered table-hover table-striped',
        url: '/order/selectCustomerProductOrderDetailList',//请求地址
        method: 'post',//请求方式
        contentType: "application/x-www-form-urlencoded",//请求内容类型
        dataType: "json",//数据类型
        striped: true,//是否显示行间隔色
        sortable: true,//是否启用排序
        sortOrder: "desc",//排序方式
        sortName: 'createTm',//排序字段
        cache: false,//是否使用缓存
        showColumns: false,//显示隐藏列
        showRefresh: false,//显示刷新按钮
        showToggle: false,//切换显示样式
        showFooter: false,//显示Table脚部
        pagination: true,//是否显示分页
        showPaginationSwitch: false,//是否显示分页按钮
        clickToSelect: false,//是否启用点击选中行
        singleSelect: false,
        minimumCountColumns: 2,//最少要显示的列数
        undefinedText: '',//cell没有值时显示
        sidePagination: "server",//分页方式：client客户端分页，server服务端分页
        uniqueId: 'productOrderDetailId',
        idField: 'orderRelationId',
        pageSize: 5,//每页的记录行数
        pageNumber: 1,//初始化加载第1页，默认第1页
        pageList: "[5]",//可供选择的每页的行数
        fixedColumns: true,     // 冻结列
        fixedNumber: 1,         // 左侧固定列
        fixedRightNumber: 1,    // 右侧固定列
        queryParams: function (params) {
            var temp = {
                pageSize: params.limit,         // 每页数据量
                pageIndex: (params.offset / params.limit) + 1,
                productOrderId: orderId, //$('#productOrderId').val()
                productOrderDetailType: '2'
            };
            return temp;
        },
        columns: [
            {title: '主键', field: 'orderRelationId', visible: false},
            {title: '序号', field: 'index', align: 'left', valign: 'middle', width: '80', formatter: indexFormat},//
            {title: '活动名称', field: 'orderDetailName', align: 'left', valign: 'middle'},
            {title: '活动原价',field: 'productOriginalPrice', align: 'left',valign: 'middle'},
            {title: '活动成交价', field: 'productFinalPrice', align: 'left', valign: 'middle'},
            {title: '产品数量',field: 'productQuantity', align: 'left', valign: 'middle'}

        ],
        responseHandler: function (result) {
            if (result.code == "000000") {
                var obj = {
                    "rows": result.data,
                    "total": result.totalRecords//总条数
                };
            } else {
                var obj = {
                    "total": 0,
                    "rows": [],
                }
            }
            return obj;
        },
        onLoadSuccess: function () {
            //加载成功时执行
            // table列可拖动宽度
            $('.JCLRgrips').remove();
            $('#activityProductTable').css({
                minWidth: $('#activityProductTable').width()
            })
            //     .colResizable({
            //     resizeMode: 'overflow',
            //     liveDrag: true,
            //     gripInnerHtml: "<div class='grip'></div>",
            //     draggingClass: "dragging",
            //     disabledColumns: [0],      // 禁止拖动的列
            //     postbackSafe: true,                                         // 刷新后保持拖动的宽度
            //     partialRefresh: true,                                       // 刷新表格之后继续保持可拖动功能
            //     flush: true,
            //     minWidth: 80,
            // });
        },
        detailView: true,
        detailFormatter: function(index,row){
            var html = '';
            var productOrderId =orderId //$('#productOrderId').val();
            $.ajax({    // 获取活动相关产品
                type: "post",
                url: "/order/selectCustomerOrderActivityRelationById",
                data: {
                    productOrderId: productOrderId,
                    orderRelationId: row.orderRelationId
                },
                dataType: 'json',
                async: false,
                success: function (data, status) {
                    if(data.code == '000000') {
                        var customerProductList = data.data;
                        if(customerProductList){
                            for (var i = 0; i < customerProductList.length; i++) {
                                html += '<span class="label label-info">' + customerProductList[i].productName + '</span>';
                            }
                        }
                    }
                }
            });
            return html;
        },
        onPostBody(data) {
            $('#activityProductTable').bootstrapTable('expandAllRows');     // 展开所有行
        }
    });
}

/**
 * 赠品详情--分页列表页
 */
function giftDetailTableInit() {
    //先销毁表格
    $giftDetailTable.bootstrapTable('destroy');
    $giftDetailTable.bootstrapTable({
        classes: 'table table-bordered table-hover table-striped',
        url: '/order//selectCustomerOrderGiftRelationList',//请求地址
        method: 'post',//请求方式
        contentType: "application/x-www-form-urlencoded",//请求内容类型
        dataType: "json",//数据类型
        striped: true,//是否显示行间隔色
        sortable: true,//是否启用排序
        sortOrder: "desc",//排序方式
        sortName: 'createTm',//排序字段
        cache: false,//是否使用缓存
        showColumns: false,//显示隐藏列
        showRefresh: false,//显示刷新按钮
        showToggle: false,//切换显示样式
        showFooter: false,//显示Table脚部
        pagination: true,//是否显示分页
        showPaginationSwitch: false,//是否显示分页按钮
        clickToSelect: false,//是否启用点击选中行
        singleSelect: false,
        minimumCountColumns: 2,//最少要显示的列数
        undefinedText: '',//cell没有值时显示
        sidePagination: "server",//分页方式：client客户端分页，server服务端分页
        uniqueId: 'orderGiftRelationId',
        idField: 'orderGiftRelationId',
        pageSize: 5,//每页的记录行数
        pageNumber: 1,//初始化加载第1页，默认第1页
        pageList: "[5]",//可供选择的每页的行数
        fixedColumns: true,     // 冻结列
        fixedNumber: 1,         // 左侧固定列
        fixedRightNumber: 1,    // 右侧固定列
        queryParams: function (params) {
            var temp = {
                pageSize: params.limit,         // 每页数据量
                pageIndex: (params.offset / params.limit) + 1,
                productOrderId: orderId, //$('#productOrderId').val()
            };
            return temp;
        },
        columns: [
            {title: '主键', field: 'orderGiftRelationId', visible: false},
            {title: '序号', field: 'index', align: 'left', valign: 'middle', width: '80', formatter: indexFormat},//
            {title: '产品名称', field: 'productGiftName', align: 'left', valign: 'middle',},
            {title: '产品原价', field: 'productOriginalPrice', align: 'left', valign: 'middle'},
            {title: '产品单价', field: 'productUnitPrice', align: 'left', valign: 'middle'}

        ],
        responseHandler: function (result) {
            if (result.code == "000000") {
                var obj = {
                    "rows": result.data,
                    "total": result.totalRecords//总条数
                };
            } else {
                var obj = {
                    "total": 0,
                    "rows": [],
                }
            }
            return obj;
        },
        onLoadSuccess: function () {
            //加载成功时执行
            // table列可拖动宽度
            $('.JCLRgrips').remove();
            $('#giftDetailTable').css({
                minWidth: $('#giftDetailTable').width()
            })
            //     .colResizable({
            //     resizeMode: 'overflow',
            //     liveDrag: true,
            //     gripInnerHtml: "<div class='grip'></div>",
            //     draggingClass: "dragging",
            //     disabledColumns: [0],                                     // 禁止拖动的列
            //     postbackSafe: true,                                         // 刷新后保持拖动的宽度
            //     partialRefresh: true,                                       // 刷新表格之后继续保持可拖动功能
            //     flush: true,
            //     minWidth: 80,
            // });
        },
    });
}


/**
 * 审核结果
 */
function findAuditTableInit() {
    //先销毁表格
    $findAudit.bootstrapTable('destroy');
    $findAudit.bootstrapTable({
        classes: 'table table-bordered table-hover table-striped',
        url: '/contractReview/getContractReviewResultList',//请求地址
        method: 'get',//请求方式
        dataType: "json",//数据类型
        striped: true,//是否显示行间隔色
        sortable: true,//是否启用排序
        sortOrder: "desc",//排序方式
        sortName: 'createTm',//排序字段
        cache: false,//是否使用缓存
        showColumns: false,//显示隐藏列
        showRefresh: false,//显示刷新按钮
        showToggle: false,//切换显示样式
        showFooter: false,//显示Table脚部
        pagination: true,//是否显示分页
        showPaginationSwitch: false,//是否显示分页按钮
        clickToSelect: false,//是否启用点击选中行
        singleSelect: false,
        minimumCountColumns: 2,//最少要显示的列数
        undefinedText: '',//cell没有值时显示
        sidePagination: "server",//分页方式：client客户端分页，server服务端分页
        uniqueId: 'orderGiftRelationId',
        idField: 'orderGiftRelationId',
        pageSize: 5,//每页的记录行数
        pageNumber: 1,//初始化加载第1页，默认第1页
        pageList: "[5]",//可供选择的每页的行数
        fixedColumns: true,     // 冻结列
        fixedNumber: 1,         // 左侧固定列
        fixedRightNumber: 1,    // 右侧固定列
        queryParams: function (params) {
            var temp = {
                pageSize: params.limit,         // 每页数据量
                pageIndex: (params.offset / params.limit) + 1,
                contractId: contractId,
            };
            return temp;
        },
        columns: [
            {title: '主键', field: 'contractReviewId', visible: false},
            {title: '序号', field: 'index', align: 'left', valign: 'middle', width: '80', formatter: indexFormat},//
            {title: '审核不符合类型', field: 'contractReviewTypeName', align: 'left', valign: 'middle',},
            {title: '审核备注', field: 'contractReviewNotes', align: 'left', valign: 'middle'},
            {title: '处理结果', field: 'processResultName', align: 'left', valign: 'middle'},
            {title: '审核时间', field: 'createTm', align: 'left', valign: 'middle'},
            {title: '审核人', field: 'createPeopleName', align: 'left', valign: 'middle'}

        ],
        responseHandler: function (result) {
            if (result.code == "000000") {
                var obj = {
                    "rows": result.data,
                    "total": result.totalRecords//总条数
                };
                if(result.data.length>0){
                    // $('#finalResult').html(result.data[0].processResultName)
                    if(result.data[0].processResultName=='通过'){
                        $('#finalResult').addClass("pass");
                        $("#judgeProhibit").attr("disabled",true)
                        // $("#editSaveSwitch").attr("disabled",true)
                    }else{
                        $('#finalResult').addClass("nopass");
                        $("#judgeProhibit").attr("disabled",false)
                        // $("#editSaveSwitch").attr("disabled",false)
                    }
                }

            } else {
                var obj = {
                    "total": 0,
                    "rows": [],
                }
            }
            return obj;
        },
        onLoadSuccess: function () {
            //加载成功时执行
            // table列可拖动宽度
            $('.JCLRgrips').remove();
            $('#giftDetailTable').css({
                minWidth: $('#giftDetailTable').width()
            })
            //     .colResizable({
            //     resizeMode: 'overflow',
            //     liveDrag: true,
            //     gripInnerHtml: "<div class='grip'></div>",
            //     draggingClass: "dragging",
            //     disabledColumns: [0],                                     // 禁止拖动的列
            //     postbackSafe: true,                                         // 刷新后保持拖动的宽度
            //     partialRefresh: true,                                       // 刷新表格之后继续保持可拖动功能
            //     flush: true,
            //     minWidth: 80,
            // });
        },
    });
}

//添加合同审核
function addContractReview(element){
    //合同id
    // var contractId =sessionStorage.getItem('contractId');
    var contractId =$("#contractId").val();
    //审核不符类型
    var contractReviewType = $('#contractReviewType').val();
    //处理结果
    var processResult = $('#processResult').val();
    //备注
    var contractReviewNote = $('#contractReviewNote').val();
    //合同编号
    var contractNumber = $('#contractNumber').val();
    //商机id
    var opportunityId = $('#opportunityId').text();

    if (!processResult) {
        promptInfo("处理结果必填！");
        return;
    }

    if (processResult!='2'&&!contractReviewType) {
        promptInfo("审核不符类型必填！");
        return;
    }
    $(element).prop('disabled', true);
    var jsonData = {
        "contractId":contractId,
        "contractReviewType":contractReviewType,
        "processResult":processResult,
        "contractReviewNotes":contractReviewNote,
        "contractNumber":contractNumber,
        "opportunityId":opportunityId
    };

    $.ajax({
        url: '/contractReview/addContractReview',
        type: 'POST',
        dataType: "json",
        contentType: "application/json;charset=utf-8",
        data: JSON.stringify(jsonData),
        success: (function (data) {
            if(data.code == '000000'){
                $.alert({
                    title: '提示',
                    content: '保存成功！',
                    buttons: {
                        confirm: {
                            text: '确认',
                            btnClass: 'btn-primary',
                            action: function () {
                                //刷新表格
                                $findAudit.bootstrapTable('refresh');
                                //隐藏添加合同审核
                                hideAddContractReview();
                                $(element).prop('disabled', false);
                            }
                        }
                    }
                });
            } else if(data.code == 'PG0001'){
                //活动名称重复
                $.alert(data.message);
                $(element).prop('disabled', false);
            } else if (data.code == 'CR0001') {
                $.alert({
                    title: '提醒',
                    content: '此合同已经被审核通过，不能重复审核！',
                    buttons: {
                        confirm: {
                            text: '确认',
                            btnClass: 'btn-primary',
                            action: function () {
                                // 刷新页面
                                window.location.reload();
                            }
                        }
                    }
                });
            } else {
                $.alert("保存失败");
                $(element).prop('disabled', false);
            }
        }),
        error: (function (res) {
            $.alert("保存失败");
            $(element).prop('disabled', false);
        })
    })
}

function hideAddContractReview() {
    $("#addFindAudit").modal('hide')
}
function showInput() {
    //审核不符类型
    var contractReviewType = $('#contractReviewType').val('');
    //处理结果
    var processResult = $('#processResult').val('');
    //备注
    var contractReviewNote = $('#contractReviewNote').val('');
    $("#addFindAudit").modal('show')
}

/**
 * 提示信息
 * @param content 提示内容
 */
function promptInfo(content) {
    $.alert({
        title: '温馨提示',
        content: content,
        buttons: {
            confirm: {
                text: '确认',
                btnClass: 'btn-primary'
            }
        }
    });
}


$("#processResult").on("change",function(){
    if ($(this).val() == '2'){
        $("#contractReviewType").attr("disabled",true)
    }else {
        $("#contractReviewType").attr("disabled",false)
    }
})



// // 附加费用
// $('#surcharge').on('change', function () {
//     if ($(this).val() == '' || $(this).val() == '0') {
//         $('.surcharge-remarks').hide();
//     } else {
//         $('.surcharge-remarks').show();
//     }
// })

// 优惠价格为0时，隐藏审批上传图片
// $('#discountAmount').html() == '0' ? $('.approval').hide(0) : $('.approval').show(0);

/**
 * 优惠券列表 - 自定义内容
 * */
var couponFormat = {
    couponType: function (value, row, index, field) {
        if (value == '1') {
            return '折扣类'
        } else {
            return '额度类'
        }
    },
    // operation: function (value, row, index, field) {
    //     return '<button type="button" class="btn btn-default btn-danger" onclick="removeRow(this, \'' + row.chsCustomerCouponId + '\')"><i class="mdi mdi-delete"></i>删除</button>';
    // }
}

// 优惠券列表
function couponTableInit() {
    //先销毁表格
    $('#couponTable').bootstrapTable('destroy');
    $('#couponTable').bootstrapTable({
        classes: 'table table-bordered table-hover table-striped',
        url: '/contractCoupon/selectContractCouponByContractId?contractId='+contractId+'',//请求地址
        method: 'get',//请求方式
        contentType: "application/x-www-form-urlencoded",//请求内容类型
        dataType: "json",//数据类型
        striped: true,//是否显示行间隔色
        sortable: true,//是否启用排序
        sortOrder: "desc",//排序方式
        sortName: 'createTm',//排序字段
        cache: false,//是否使用缓存
        showColumns: false,//显示隐藏列
        showRefresh: false,//显示刷新按钮
        showToggle: false,//切换显示样式
        showFooter: false,//显示Table脚部
        pagination: false,//是否显示分页
        showPaginationSwitch: false,//是否显示分页按钮
        clickToSelect: false,//是否启用点击选中行
        singleSelect: false,
        minimumCountColumns: 2,//最少要显示的列数
        undefinedText: '-',//cell没有值时显示
        sidePagination: "server",//分页方式：client客户端分页，server服务端分页
        uniqueId: 'orderGiftRelationId',
        idField: 'orderGiftRelationId',
        pageSize: 5,//每页的记录行数
        pageNumber: 1,//初始化加载第1页，默认第1页
        pageList: "[5]",//可供选择的每页的行数
        columns: [
            {title: '主键', field: 'chsCustomerCouponId', visible: false},
            {title: '序号', field: 'index', align: 'left', valign: 'middle', width: '60', formatter: indexFormat},
            {title: '优惠券名称',field: 'couponName', align: 'left', valign: 'middle'},
            //, formatter: couponFormat.couponType
            {title: '优惠券类型', field: 'couponType',align: 'left', valign: 'middle', formatter: couponFormat.couponType},
            {title: '优惠券额度', field: 'couponQuota',align: 'left', valign: 'middle'},
            {title: '优惠券优惠折扣', field: 'couponDiscount',align: 'left', valign: 'middle'},
            //, formatter: couponFormat.operation
            // {title: '操作', field: 'giftOperate', align: 'right', valign: 'middle'},
        ],
        responseHandler: function (result) {
            console.log(result)
            if (result.code == "000000") {
                var obj = {
                    "rows": result.data,
                };
            } else {
                var obj = {
                    "rows": [],
                }
            }
            return obj;
        },
        onLoadSuccess: function () {
            //加载成功时执行
        },
    });
}

//审核合同时跳转客户详情
$("#customerNameRepeat").click(function(){
    //客户id
    var customerId = $("#customerId").val();
    //客户类型
    var customerType = $("#customerType").val();
    //客户名称
    var customerName = $("#customerNameRepeat").val();
    //联系方式
    var contactDetails = $('#contactDetails').val().replace('-','');
    //跳转
    if(customerType == 1){//个人客户
        contactNameDetail(customerName,contactDetails,customerId);
    }else if(customerType == 0){//企业客户
        customerDetail(customerId);
    }
});

/**
 * 合同审核(个人客户)--客户名称列点击事件(客户详情)
 * @param customerName
 * @param contactPersonPhone
 */
function contactNameDetail (customerName, contactPersonPhone, customerId) {
    var contactId = "";
    //查询联系人id,进行跳转
    $.ajax({
        url: '/contact/getCustomerIdAndContactNameAndAccountId',
        type: 'POST',
        dataType: "json",
        data: {
            customerId,
            contactName: customerName,
            contactInformation : contactPersonPhone,
            contactNature : '1',
            csd : 'csd'
        },
        success: (function (data) {
            if (data.code == "000000") {
                if (data.data.contactId != null) {
                    contactId = data.data.contactId;
                    parent.$(parent.document).data('multitabs').create({
                        iframe: true,
                        title: '联系人详情',
                        url: "/front/user/contactManager/contactDetail?contactId=" + contactId
                    },true);
                }else{
                    $.alert("数据有问题,请重试!");
                }
            } else {
                alert("操作失败");
            }
        }),
        error: (function () {
            alert("失败");
        })
    });
}

/**
 * 合同审核(企业客户)--客户名称列点击事件(客户详情)
 * @param customerId
 */
function customerDetail (customerId) {
    parent.$(parent.document).data('multitabs').create({
        iframe : true,
        title : '客户详情',
        url : "/front/user/customerManager/customerDetail?customerId=" + customerId + "&csd=csd"
    }, true);
}

//主会员合同跳转
$("#masterMembershipContract").click(function(){
    //主会员合同id
    var masterMembershipContractId = $("#masterMembershipContractId").val();
    parent.$(parent.document).data('multitabs').create({
        iframe : true,
        title : '合同详情',
        url : "/front/contractManager/contractDetail?contractId=" + masterMembershipContractId
    }, true);
});

//返回上一页面
function backBtn(){
    openTab("合同审核","/front/contractReviewManager/contractReviewForm");
    refreshActivePane('/front/contractReviewManager/contractReviewForm');
}
/**
 * 功能：提醒弹窗
 * */
function promptInfo(content) {
    $.alert({
        title: '温馨提示',
        content: content,
        buttons: {
            confirm: {
                text: '确认',
                btnClass: 'btn-primary'
            }
        }
    });
}
//打开 关联记录
function openFollowUpDetail(){
    if(clueFollowId){
        getFollowInfo()
    }
    if(opportunityIds){
        pageIndex=1;
        $("#followList").html("");
        getOpportunityInfo(pageIndex,pageSize);
    }
    $("#followUpDetail").animate({width:"660px",padding:"20px"});
    $(".closeBtn").show();
}
//关闭 关联记录
function closeFollowUpDetail(){
    $("#followUpDetail").animate({width:0,padding:0});
    $(".closeBtn").hide();
    $("#followList").html("");
}
//获得跟进信息
function getFollowInfo(){
    $.ajax({
        url: '/contractReview/getFollowRecordDetailById?clueFollowId='+clueFollowId,
        type: 'GET',
        datatype: 'json',
        success: function (data) {
            if(data.code === "000000"){
                let followSource = data.data.followSource;
                $("#personName").html(followSource==6?data.data.personName:data.data.contactName);
                // $("#visitAddress").html(data.data.visitAddress);
                let customerQuality = data.data.customerQuality;
                switch(customerQuality){
                    case 1:
                        customerQuality="优";
                        break;
                    case 2:
                        customerQuality="良";
                        break;
                    case 3:
                        customerQuality="一般";
                        break;
                };
                let followWay = data.data.followWay;
                switch(followWay){
                    case 1:
                        followWay="线上电话";
                        break;
                    case 2:
                        followWay="拜访";
                        break;
                    case 3:
                        followWay="微信";
                        break;
                    case 4:
                        followWay="线下电话";
                        break;
                    case 5:
                        followWay="邮箱";
                        break;
                    case 6:
                        followWay="陪访";
                        break;
                };

                $("#followWay").html('跟进方式-('+followWay+')');
                $("#userPhone").html(followSource==6?data.data.personPhone:data.data.contactInformation);
                $("#followTm").html(data.data.followTm);

                let followPurpose = data.data.followPurpose;
                switch(followPurpose){
                    case '1':
                        followPurpose="产品跟进";
                        break;
                    case '2':
                        followPurpose="过程跟进";
                        break;
                    case '3':
                        followPurpose="商机跟进";
                        break;
                };

                if(data.data.followWay==2){
                    //陪访人
                    $("#accompanyingPerson").html(data.data.accompanyingPerson);
                }else{
                    $("#accompanyingPersonCon").hide()
                }
                if(data.data.followWay!=1){
                    $("#customerQuality").html(customerQuality);
                    $("#nextPlanTime").html(data.data.nextPlanTime);
                    $("#customerIntention").html(data.data.customerIntention?data.data.customerIntention+"%":'');
                    $("#followPurpose").html(followPurpose);
                    $("#clueScore").attr({'data-score':data.data.clueScore});
                    //绘制线索评分星星
                    initScore();
                }else{
                    $("#customerQualityCon").hide();
                    $("#nextPlanTimeCon").hide();
                    $("#customerIntentionCon").hide();
                    $("#followPurposeCon").hide();
                    $("#clueScoreCon").hide();
                    $("#tagsCon").hide();
                }
                $("#communicationTime").html(data.data.communicationTime?data.data.communicationTime:0);
                $("#followDetail").html(data.data.followDetail?data.data.followDetail:'(无跟进详情)');

            } else {
                promptInfo(data.message);
            }

        },
        error: function (message) {
            promptInfo(message);
        }
    })
}
//获得商机动态信息
function getOpportunityInfo(pageIndex, pageSize) {
    var jsonData = {
        opportunityId:opportunityIds,
        pageIndex: pageIndex,
        pageSize: pageSize,
        sortName: 'createTm',
        sortOrder: 'desc'
    }
    $.ajax({
        url: '/opportunity/opportunityDynamicList',
        type: 'post',
        dataType: 'json',
        async: true,
        data: jsonData,
        success: function (data) {
            if (data.code == '000000') {
                var newData = data.data;
                totalNum = data.totalRecords;
                if (newData.length != 0) {
                    newData.forEach((value) => {
                        var followWay;
                        var opportunityStatus=value.opportunityStatus;
                        var opportunityContent;
                        if(value.operationMode===0){
                            //操作方式为 0-跟进时
                            switch (Number(value.followWay)) {
                                case 1: followWay = '线上电话'; break;
                                case 2: followWay = '拜访'; break;
                                case 3: followWay = '微信'; break;
                                case 4: followWay = '线下电话'; break;
                                case 5: followWay = '邮箱'; break;
                                case 6: followWay = '陪访'; break;
                                default: followWay = '';break;
                            };
                            opportunityContent = value.followDetail;
                        }else if(value.operationMode===1){
                            //操作方式为 1-修改商机状态
                            followWay = '状态修改';
                            switch(opportunityStatus){
                                case '1':
                                    opportunityContent = "初步洽谈";
                                    break;
                                case '2':
                                    opportunityContent = "需求确定";
                                    break;
                                case '3':
                                    opportunityContent = "方案报价";
                                    break;
                                case '4':
                                    opportunityContent = "谈判";
                                    break;
                                case '5':
                                    opportunityContent = "洽谈合同";
                                    break;
                                case '6':
                                    opportunityContent = "赢单";
                                    break;
                                case '7':
                                    opportunityContent = "输单";
                                    break;
                                default:
                                    opportunityContent = "";
                                    break;
                            };
                            opportunityContent = opportunityContent?`将商机状态修改为<span class="label label-warning">${opportunityContent}</span>`:'';
                        };
                        var htmlStr=`<div class="followLi clearFix" >
                                        <div class="followImg">
                                            <span class="headPortrait">
                                                <img src="${value.accessUrl}" alt="">
                                            </span>
                                            <span class="businessStatus">${followWay}</span>
                                        </div>
                                        <div class="followContent">
                                            <div>
                                                <span class="title">跟进人:</span>
                                                <span class="personNames">${value.userName}</span>
                                                <span>/</span>
                                                <span class="time">${new Date(value.createTm).Format("yyyy-MM-dd hh:mm:ss")}</span>
                                            </div>
                                            <div>${opportunityContent}</div>
                                        </div>
                                    </div>`;
                        $("#followList").append(htmlStr);
                    })
                }else{
                    $('#followList').html('<p class="nodata">暂无跟进记录</p>');
                }
            } else{
                promptInfo(data.message);
            }
        },
        error: function (message) {
            promptInfo(message)
        }
    })
}
//表单校验
function formValidator(){
    $('#customerForm').bootstrapValidator({
        fields: {
            contractType: {
                validators: {
                    notEmpty: {
                        message: '合同类型不能为空'
                    }
                }
            },
            contractDate: {
                validators: {
                    notEmpty: {
                        message: '合同起止日期不能为空'
                    }
                }
            },
            contactName: {
                validators: {
                    notEmpty: {
                        message: '客户联系人不能为空'
                    }
                }
            },
            contactDetails: {
                validators: {
                    notEmpty: {
                        message: '联系方式不能为空'
                    }
                }
            },
            customerEmail: {
                validators: {
                    notEmpty: {
                        message: '邮箱不能为空'
                    },
                    emailAddress: {
                        message: '邮箱格式有误'
                    }
                }
            }
        }
    });
}
// 评分插件
function initScore() {
    jQuery(".js-raty").each(function () {
        var a = jQuery(this);
        a.raty({
            starType: "i",
            targetText: a.data("target-text") ? a.data("target-text") : '',
            score: a.data("score") ? a.data("score") : 0,
            number: a.data("number") ? a.data("number") : 5,
            cancel: a.data("cancel") ? a.data("cancel") : !1,
            target: a.data("target") ? a.data("target") : !1,
            targetScore: a.data("target-score") ? a.data("target-score") : !1,
            precision: a.data("precision") ? a.data("precision") : !1,
            cancelOff: a.data("cancel-off") ? a.data("cancel-off") : "mdi mdi-close fa-1-5x text-danger",
            cancelOn: a.data("cancel-on") ? a.data("cancel-on") : "mdi mdi-close fa-1-5x",
            starHalf: a.data("star-half") ? a.data("star-half") : "mdi mdi-star-half fa-1-5x text-warning",
            starOff: a.data("star-off") ? a.data("star-off") : "mdi mdi-star fa-1-5x text-gray",
            starOn: a.data("star-on") ? a.data("star-on") : "mdi mdi-star fa-1-5x text-warning",
            readOnly: true,
            // click: function (score, e) {
            // }
        })
    })
}

function mySwiper() {
    var pageNumber;
    new Swiper('.swiper-container', {
        observer:true,
        observeParents: true,
        spaceBetween: 30,
        effect: 'fade',
        loop: true,
        // autoplay: true,
        delay: 300,
        pagination: {
            el: '.swiper-pagination',
            clickable: true,
        },
        navigation: {
            nextEl: '.swiper-button-next',
            prevEl: '.swiper-button-prev',
        },
        on: {
            slideChangeTransitionStart: function () {
                var index = Number(this.activeIndex);
                console.log(index);
                if (index == 4) {
                    index = 1
                }
                if (index == 0) {
                    index = 3;
                }
                pageNumber = index;
            }
        },
    });
}
//查看图片
// function viewBtn(){
//     mySwiper();
//     $('#visitImg').modal('show');
// }
//滚动加载商机动态
 $('#dynamic').scroll(function(){
     var scrollTop = $(this).scrollTop();
     var scrollHeight = $("#followList").height();
     var windowHeight = $(this).height();
     if(scrollTop + windowHeight + 10 >= scrollHeight){
         if(pageIndex*pageSize<totalNum){
             pageIndex++;
             getOpportunityInfo(pageIndex,pageSize)
         }
     }
 })

var productEvents = {

    'click #recordConsumption': function (e, value, row, index) {
        getRecordConsumption(row,0);
    }
}
function memberFinishOrderProductOpt(value, row, index) {
    // if(row.productStatus == '3'){
    // // <button type="button" id="productDetail" class="btn btn-default"><i class="mdi mdi-note-outline"></i>详细信息</button>
    //     var html =  '';
    //
    //     html += '<button type="button" id="recordConsumption" class="btn btn-default"><i class="mdi mdi-format-list-bulleted"></i>消费记录</button>';
    //
    //     return html;
    // }else{
    //     return ''
    // }

    var html =  '';

    html += '<button type="button" id="recordConsumption" class="btn btn-default"><i class="mdi mdi-format-list-bulleted"></i>查看消费</button>';

    return html;

}
function getRecordConsumption(data,bs){
    // var rowData = data;
    console.log(data,'data==>')
    $.ajax({
        url: '/customerController/selectCustomerProductDetail',
        type: 'POST',
        dataType: "json",
        data: {
            customerId: data.currentCustomerId,                                              // 客户id
            memberProductId: data.currentProductId,                         // 会员产品id currentProductId
            finishOrderProductNum: data.currentFinishOrderProductNum,        // 产品号
            orderId:data.currentOrderId == null?'0':data.currentOrderId , // 订单id currentOrderId
            memberProductCode:data.currentProductCode == null?'0': data.currentProductCode,// 产品编码 currentProductCode
            bs:1  //  0 会员 1非会员
        },
        success: (function (data) {
            console.log(data,'data')
            if(data.code=='000000'){
                if (data.data.customerProductDetailMemberCard == null) {
                    // 无会员卡
                    $.alert('您还没有申请会员卡,请先申请!');
                } else {
                    // 有会员卡
                    var cardData = data.data.customerProductDetailMemberCard[0];
                    console.log('有会员卡');
                    var ifHou =  $("#ifHou").val();//是否是侯欣雪
                    var url = 'https://nsrjlb.com/m/m_xuanchan/cardRecording.php?name=' + cardData.memberCardNumber + "&ifHou=" + ifHou;
                    $('#expensesRecordIframe').attr('src', url)
                    $('#expensesRecordIframe').css('width', '100%')
                    $('#expensesRecordIframe').css('height', '550px')
                    $('#expensesRecord').modal('show')
                }
            }

        })
    })
}

/*产品详情table1*/
function initViewList(){
    $viewSumption.bootstrapTable('destroy');
    $viewSumption.bootstrapTable({
        classes: 'table table-bordered table-hover table-striped',
        url:"/upgradeContract/getUpgradeContractDetail",
        method: 'get',//请求方式
        // method: 'post',//请求方式
        contentType: "application/x-www-form-urlencoded",//请求内容类型
        // contentType:"application/json;charset=utf-8",
        dataType: "json",                   // 数据类型
        striped: true,                      // 是否显示行间隔色
        sortable: true,                     // 是否启用排序
        sortOrder: "desc",                  // 排序方式
        sortName: 'createTm',               // 排序字段
        cache: false,                       // 是否使用缓存
        showColumns: false,                 // 显示隐藏列
        showRefresh: false,                 // 显示刷新按钮
        showToggle: false,                  // 切换显示样式
        showFooter: false,                  // 显示Table脚部
        pagination: true,                   // 是否显示分页
        showPaginationSwitch: false,        // 是否显示分页按钮
        clickToSelect: true,                // 是否启用点击选中行
        maintainSelected: true,             // 分页是否保留选中
        singleSelect: false,
        minimumCountColumns: 2,             // 最少要显示的列数
        undefinedText: '-',                  // cell没有值时显示
        sidePagination: "server",           // 分页方式：client客户端分页，server服务端分页

        uniqueId: 'currentContractId',
        idField: 'currentContractId',
        pageSize: 1,                        // 每页的记录行数
        pageNumber: 1,                      // 初始化加载第1页，默认第1页
        pageList: "[5, 10, 15, 20]",        // 可供选择的每页的行数

        queryParams: function (params) {
            // 20388f3c808847929152ba3b5adaf5b4   $("#contractId").val()
            // params.contractId='20388f3c808847929152ba3b5adaf5b4'
            params.contractId=$("#contractId").val()
            return params
        },//查询参数
        columns: [

            {title: '主键', field: 'currentContractId', visible: false},
            {title: '序号', field: 'index', align: 'left', valign: 'middle', width: '52', formatter: indexFormat},
            {title: '兑换前产品', field: 'currentProductName', align: 'left', valign: 'middle'},
            {title: '兑换前产品成交价', field: 'currentProductDealPrice', align: 'left', valign: 'middle'},
            {title: '操作', field: 'operate', align: 'right', width: '80', events: productEvents, formatter: memberFinishOrderProductOpt}
        ],
        responseHandler: function (result) {
            if(result.code == "000000") {
                var obj = {

                    "rows": [result.data],
                    "total": 1//总条数
                };

                $("#contactUpgrade").text(result.data.currentContractNumber);
                $("#currentContractId").val(result.data.currentContractId)
                $("#currentOrderId").val(result.data.currentOrderId)





            } else {
                var obj = {
                    "total": 0,
                    "rows": [],
                }
            }
            return obj;
        },
        onLoadSuccess: function () {

        },
        onLoadError: function (status) {
            if (status == 403) {
                alert("权限不足！禁止访问！");
            } else {
                //加载失败时执行
                // alert("加载失败！");
            }
        },
        formatLoadingMessage: function () {
            return "请稍等，加载中...";
        },
        formatNoMatches: function () {
            return '无符合条件的记录';
        },
    });
}

/*产品详情table2*/
function initAdjustList(){
    $adjustMent.bootstrapTable('destroy');
    $adjustMent.bootstrapTable({
        classes: 'table table-bordered table-hover table-striped',
        url:"/upgradeContract/getUpgradeContractDetail",
        method: 'get',//请求方式
        // method: 'post',//请求方式
        contentType: "application/x-www-form-urlencoded",//请求内容类型
        // contentType:"application/json;charset=utf-8",
        dataType: "json",                   // 数据类型
        striped: true,                      // 是否显示行间隔色
        sortable: true,                     // 是否启用排序
        sortOrder: "desc",                  // 排序方式
        sortName: 'createTm',               // 排序字段
        cache: false,                       // 是否使用缓存
        showColumns: false,                 // 显示隐藏列
        showRefresh: false,                 // 显示刷新按钮
        showToggle: false,                  // 切换显示样式
        showFooter: false,                  // 显示Table脚部
        pagination: true,                   // 是否显示分页
        showPaginationSwitch: false,        // 是否显示分页按钮
        clickToSelect: true,                // 是否启用点击选中行
        maintainSelected: true,             // 分页是否保留选中
        singleSelect: false,
        minimumCountColumns: 2,             // 最少要显示的列数
        undefinedText: '-',                  // cell没有值时显示
        sidePagination: "server",           // 分页方式：client客户端分页，server服务端分页

        uniqueId: 'currentContractId',
        idField: 'currentContractId',
        pageSize: 1,                        // 每页的记录行数
        pageNumber: 1,                      // 初始化加载第1页，默认第1页
        pageList: "[5, 10, 15, 20]",        // 可供选择的每页的行数

        queryParams: function (params) {
            params.contractId=$("#contractId").val()
            return params
        },//查询参数
        columns: [

            {title: '主键', field: 'currentContractId', visible: false},
            {title: '序号', field: 'index', align: 'left', valign: 'middle', width: '52', formatter: indexFormat},
            {title: '补款后产品', field: 'updateProductName', align: 'left', valign: 'middle'},
            {title: '补款产品会员价', field: 'updateProductMemberPrice', align: 'left', valign: 'middle'},
            {title: '补款金额', field: 'replenishmentAmount', align: 'left', valign: 'middle'},
            // {title: '操作', field: 'couponDiscount', align: 'right', valign: 'middle', width: '120', },
        ],
        responseHandler: function (result) {
            if(result.code == "000000") {
                var obj = {

                    "rows": [result.data],
                    "total": 1//总条数
                };




            } else {
                var obj = {
                    "total": 0,
                    "rows": [],
                }
            }
            return obj;
        },
        onLoadSuccess: function () {

        },
        onLoadError: function (status) {
            if (status == 403) {
                alert("权限不足！禁止访问！");
            } else {
                //加载失败时执行
                // alert("加载失败！");
            }
        },
        formatLoadingMessage: function () {
            return "请稍等，加载中...";
        },
        formatNoMatches: function () {
            return '无符合条件的记录';
        },
    });
}

function openDetail() {
    parent.$(parent.document).data('multitabs').create({
        iframe : true,
        title : '审核详情',
        url :"/front/contractReviewManager/contractReview?contractId=" + $("#currentContractId").val()+'&orderId='+ $("#currentOrderId").val()
    }, true);
}
